package com.huawei.handler;

import cn.hutool.json.JSONUtil;
import com.huawei.domain.ResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//用于处理认证过程中出现的异常
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        //将响应码与错误信息存放到ResponseResult中
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), "似乎认证失败了喵~");

        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        //将ResponseResult对象转换为json格式的字符串，并返回给前端
        response.getWriter().print(JSONUtil.toJsonStr(result));
    }
}
